package com.zw.yzk.kabu.view.fragment;

import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;

import com.zw.yzk.kabu.R;
import com.zw.yzk.kabu.adapter.CosplayListAdapter;
import com.zw.yzk.kabu.adapter.FameListAdapter;
import com.zw.yzk.kabu.base.BaseFragment;
import com.zw.yzk.kabu.constant.ActivityConstant;
import com.zw.yzk.kabu.data.cache.db.DataBaseManager;
import com.zw.yzk.kabu.data.cache.db.User;
import com.zw.yzk.kabu.data.network.task.CosplayListTask;
import com.zw.yzk.kabu.internal.component.DaggerDataListComponent;
import com.zw.yzk.kabu.internal.module.ActivityModule;
import com.zw.yzk.kabu.internal.module.CosplayListModule;
import com.zw.yzk.kabu.internal.module.FameListModule;
import com.zw.yzk.kabu.management.AppManager;
import com.zw.yzk.kabu.model.CosplayModel;
import com.zw.yzk.kabu.model.FameModel;
import com.zw.yzk.kabu.presenter.DataListPresenter;
import com.zw.yzk.kabu.view.activity.AuthCoserActivity;
import com.zw.yzk.kabu.view.activity.MainActivity;
import com.zw.yzk.kabu.view.activity.PublishCosplayActivity;
import com.zw.yzk.kabu.view.activity.SearchTopicActivity;
import com.zw.yzk.kabu.view.activity.SearchUserActivity;
import com.zw.yzk.kabu.view.view.DataListView;
import com.zw.yzk.kabu.view.widget.ChangeCosplayCategoryDialog;
import com.zw.yzk.kabu.view.widget.CustomAlertDialog;
import com.zw.yzk.kabu.view.widget.LoginStateInvalidDialog;
import com.zw.yzk.refresh.library.PullToRefreshLayout;
import com.zw.yzk.refresh.library.RefreshBuilder;
import com.zw.yzk.refresh.library.State;
import com.zw.yzk.refresh.library.loadmore.DefaultLoadMoreViewCreator;
import com.zw.yzk.refresh.library.refrsh.DefaultRefreshViewCreator;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import butterknife.Bind;
import butterknife.OnClick;

/**
 * Created by zhanwei on 2016/12/28.
 */

public class DataFragment extends BaseFragment implements DataListView, CosplayListAdapter.OnItemClickedListener {

    @Bind(R.id.category)
    TextView changeCategory;
    @Bind(R.id.cos_refresh_view)
    PullToRefreshLayout cosRefreshLayout;
    @Bind(R.id.cos_list)
    RecyclerView cosList;
    @Bind(R.id.fame_refresh_view)
    PullToRefreshLayout fameRefreshLayout;
    @Bind(R.id.fame_list)
    RecyclerView fameList;
    @Bind(R.id.cos_tools_bar)
    View cosToolBar;
    @Bind(R.id.no_data)
    TextView noData;

    private int dataType;
    private MainActivity activity;
    private List<CosplayModel> totalCosList;
    private List<CosplayModel> concernedList;
    private List<CosplayModel> recommendList;
    private CosplayListAdapter cosAdapter;
    private FameListAdapter fameAdapter;
    private ChangeCosplayCategoryDialog changeCosplayCategoryDialog;
    @Inject
    DataListPresenter presenter;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        activity = (MainActivity) context;
    }

    @Override
    protected int setContent() {
        return R.layout.fragment_cosplay;
    }

    @Override
    protected void initView(View view) {
        initRecyclerView();
    }

    @Override
    public void loadData() {
        initConfig();
        getCosplayList(0, true, 0);
        getFameList(0, true);
    }

    @Override
    public void initComponent() {
        DaggerDataListComponent
                .builder()
                .applicationComponent(activity.getApplicationComponent())
                .activityModule(new ActivityModule(activity))
                .fameListModule(new FameListModule())
                .cosplayListModule(new CosplayListModule())
                .build()
                .inject(this);
        presenter.setView(this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (presenter != null) {
            presenter.destroy();
        }
    }

    @Override
    public void getCosplayListSuccess(List<CosplayModel> modelList) {
        if (cosRefreshLayout.isLoading()) {
            cosAdapter.add(modelList);
            dealCosList(modelList, true);
            cosRefreshLayout.loadMoreFinish(modelList.isEmpty() ? State.LOAD_ALL : State.LOADING_SUCCEED);
        } else {
            cosAdapter.refresh(modelList);
            dealCosList(modelList, false);
            cosRefreshLayout.refreshFinish(State.REFRESH_SUCCEED);
        }
        //是否显示空提示
        setNoDataStatus(cosAdapter.getItemCount() == 0);
        //检查是否有未读消息
        activity.getUnreadCount();
    }

    @Override
    public void getCosplayListFail() {
        cosRefreshLayout.finishRefreshingOrLoadingStatus(false);
    }

    @Override
    public void getFameListSuccess(List<FameModel> modelList) {
        if (fameRefreshLayout.isLoading()) {
            fameAdapter.add(modelList);
            fameRefreshLayout.loadMoreFinish(modelList.isEmpty() ? State.LOAD_ALL : State.LOADING_SUCCEED);
        } else {
            fameAdapter.refresh(modelList);
            fameRefreshLayout.refreshFinish(State.REFRESH_SUCCEED);
        }
        //是否显示空提示
        setNoDataStatus(fameAdapter.getItemCount() == 0);
    }

    @Override
    public void getFameListFail() {
        fameRefreshLayout.finishRefreshingOrLoadingStatus(false);
    }

    @Override
    public void onPraiseClicked(CosplayModel model) {
        praise(model.getId(), model.isPraise());
    }

    @Override
    public void onCollectClicked(CosplayModel model) {
        collect(model.getId(), model.isCollected());
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == ActivityConstant.OPEN_PUBLISH_COS && resultCode == ActivityConstant.PUBLISH_COS_SUCCESS) {
            getCosplayList(0, false, 0);
        }
    }

    @OnClick(R.id.category)
    public void changeDataCategory() {
        showSelectDataDialog();
    }

    @OnClick(R.id.publish)
    public void publish() {
        User user = DataBaseManager.getInstance().getLoginUser();
        if (user == null) {
            new LoginStateInvalidDialog().showInvalidDialog(activity, activity.getResources().getString(R.string.must_login));
        } else if (!user.isLogin()) {
            new LoginStateInvalidDialog().showInvalidDialog(activity, activity.getResources().getString(R.string.must_login));
        } else if (!user.getIsFame()) {
            new CustomAlertDialog.Builder(activity, R.layout.dialog_logout)
                    .setTitle(R.id.title, activity.getResources().getString(R.string.only_fame_can_publish_cos))
                    .setNegativeButton(R.id.cancel, activity.getResources().getString(R.string.cancel))
                    .setPositiveButton(R.id.confirm, activity.getResources().getString(R.string.confirm))
                    .setOnPositiveButtonClickerListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            startActivity(new Intent(activity, AuthCoserActivity.class));
                        }
                    })
                    .setCancelable(false).build().show();
        } else {
            startActivityForResult(new Intent(activity, PublishCosplayActivity.class), ActivityConstant.OPEN_PUBLISH_COS);
        }

    }

    @OnClick(R.id.search)
    public void search() {
//        startActivity(new Intent(activity, SearchTopicActivity.class));
        startActivity(new Intent(activity, SearchUserActivity.class));
    }


    /**
     * 初始化设置
     */
    private void initConfig() {
        //默认加载全部类型
        dataType = CosplayListTask.TYPE_ALL;
        totalCosList = new ArrayList<>();
        concernedList = new ArrayList<>();
        recommendList = new ArrayList<>();
    }

    /**
     * 初始化reyclerview
     */
    private void initRecyclerView() {
        cosList.setLayoutManager(new LinearLayoutManager(activity, LinearLayoutManager.VERTICAL, false));
        cosAdapter = new CosplayListAdapter(null);
        cosAdapter.setOnItemClickedListener(this);
        cosList.setAdapter(cosAdapter);
        new RefreshBuilder.Builder(cosRefreshLayout)
                .setRefreshViewCreator(new DefaultRefreshViewCreator())
                .setLoadMoreViewCreator(new DefaultLoadMoreViewCreator())
                .setRefreshListener(new PullToRefreshLayout.OnRefreshListener() {
                    @Override
                    public void onRefresh(PullToRefreshLayout pullToRefreshLayout) {
                        getCosplayList(0, false, 0);
                    }

                    @Override
                    public void onLoadMore(PullToRefreshLayout pullToRefreshLayout) {
                        int count = cosAdapter.getItemCount();
                        getCosplayList(count, false, cosAdapter.getTotalList().get(count - 1).getId());
                    }
                }).build();

        fameList.setLayoutManager(new LinearLayoutManager(activity, LinearLayoutManager.VERTICAL, false));
        fameAdapter = new FameListAdapter(null);
        fameList.setAdapter(fameAdapter);
        new RefreshBuilder.Builder(fameRefreshLayout)
                .setRefreshViewCreator(new DefaultRefreshViewCreator())
                .setLoadMoreViewCreator(new DefaultLoadMoreViewCreator())
                .setRefreshListener(new PullToRefreshLayout.OnRefreshListener() {
                    @Override
                    public void onRefresh(PullToRefreshLayout pullToRefreshLayout) {
                        getFameList(0, false);
                    }

                    @Override
                    public void onLoadMore(PullToRefreshLayout pullToRefreshLayout) {
                        getFameList(fameAdapter.getItemCount(), false);

                    }
                }).build();
    }

    /**
     * 设置切换cosplay类型对话框
     */
    private void showSelectDataDialog() {
        if (changeCosplayCategoryDialog == null) {
            changeCosplayCategoryDialog = new ChangeCosplayCategoryDialog(activity);
            changeCosplayCategoryDialog.setOnItemChcekedListener(new ChangeCosplayCategoryDialog.OnItemCheckedListener() {
                @Override
                public void onCheck(int position) {
                    //隐藏空提示
                    setNoDataStatus(false);
                    if (position == 3) {
                        changeCategory.setText(getResources().getString(R.string.cos_celebrity_list));
                        cosRefreshLayout.setVisibility(View.GONE);
                        fameRefreshLayout.setVisibility(View.VISIBLE);
                        //获取名人堂列表
                        getFameList(0, false);
                        return;
                    } else if (position == 2) {
                        changeCategory.setText(getResources().getString(R.string.cos_concerned));
                        dataType = CosplayListTask.TYPE_CONCERNED;
                    } else if (position == 1) {
                        changeCategory.setText(getResources().getString(R.string.cos_recommend));
                        dataType = CosplayListTask.TYPE_RECOMMEND;
                    } else {
                        changeCategory.setText(getResources().getString(R.string.cos_all));
                        dataType = CosplayListTask.TYPE_ALL;
                    }
                    showCosList();
                    fameRefreshLayout.setVisibility(View.GONE);
                    cosRefreshLayout.setVisibility(View.VISIBLE);
                    //缓存列表为空，网上获取
                    getCosplayList(0, false, 0);
                    changeCosplayCategoryDialog.dismiss();
                }
            });
        }
        changeCosplayCategoryDialog.showAsDropDown(cosToolBar);
    }

    /**
     * 获取cosplay列表
     *
     * @param count 开始的索引
     */
    private void getCosplayList(int count, boolean getLocal, int lastId) {
        presenter.getCosplayList(count, getLocal, dataType, lastId);
    }


    /**
     * 获取名人榜列表
     *
     * @param count 开始的索引
     */
    private void getFameList(int count, boolean getLocal) {
        presenter.setGetFameList(count, getLocal);
    }

    /**
     * 处理获取到的数据，放到相应的列表中
     *
     * @param list    cos列表
     * @param refresh 是否是刷新操作
     */
    private void dealCosList(List<CosplayModel> list, boolean refresh) {
        switch (dataType) {
            case CosplayListTask.TYPE_ALL:
                if (refresh) {
                    totalCosList.clear();
                }
                totalCosList.addAll(list);
                break;
            case CosplayListTask.TYPE_CONCERNED:
                if (refresh) {
                    concernedList.clear();
                }
                concernedList.addAll(list);
                break;
            case CosplayListTask.TYPE_RECOMMEND:
                if (refresh) {
                    recommendList.clear();
                }
                recommendList.addAll(list);
                break;
            default:
                break;
        }
    }

    /**
     * 根据当前类型展示cos列表
     */
    private void showCosList() {
        switch (dataType) {
            case CosplayListTask.TYPE_ALL:
                cosAdapter.refresh(totalCosList);
                break;
            case CosplayListTask.TYPE_CONCERNED:
                cosAdapter.refresh(concernedList);
                break;
            case CosplayListTask.TYPE_RECOMMEND:
                cosAdapter.refresh(recommendList);
                break;
            default:
                break;
        }
    }

    /**
     * 是否显示无数据
     *
     * @param status true: 显示， false: 不显示
     */
    private void setNoDataStatus(boolean status) {
        noData.setVisibility(status ? View.VISIBLE : View.GONE);
    }

    /**
     * 是否点赞
     *
     * @param cosplayId cosid
     * @param praise    true：点赞，false：取消
     */
    public void praise(int cosplayId, boolean praise) {
        presenter.praise(cosplayId, praise);
    }

    /**
     * 是否收藏
     *
     * @param cosplayId cosId
     * @param collect   true：收藏，false：取消
     */
    public void collect(int cosplayId, boolean collect) {
        presenter.collect(cosplayId, collect);
    }

}
